#include "Widget.h"

#include <QApplication>
#include <qDebug>
#include <QFile>

QString padStringToWidth(const QString &str, int targetWidth, const QFontMetrics &metrics) {
    int currentWidth = metrics.horizontalAdvance(str);
    int spacesNeeded = (targetWidth - currentWidth) / metrics.horizontalAdvance(" ");
    return str + QString(" ").repeated(spacesNeeded);
}

QString processCommaSeparatedStrings(const QString &input, QWidget *widget) {
    QFontMetrics metrics(widget->font());
    QStringList stringList = input.split("|");

    QStringList paddedStrings;
    for (const QString &str : stringList) {
        QString paddedString = padStringToWidth(str, metrics.horizontalAdvance(QString(" ").repeated(20)), metrics);
        paddedStrings << paddedString;
    }

    return paddedStrings.join("|");
}

void processMultipleLines(const QStringList &inputLines, QWidget *widget) {
    for (const QString &line : inputLines) {
        QString processedLine = processCommaSeparatedStrings(line, widget);
        qDebug() << "Processed Line:" << processedLine;
    }
}

#include <QFile>
#include <QTextStream>
#include <QStringList>
#include <QDebug>
#include <QStandardPaths>

class FileManager {
public:
    FileManager(const QString &filePath) : filePath(filePath) {}

    // 检查文件是否存在
    bool fileExists() const {
        return QFile::exists(filePath);
    }

    // 创建文件
    bool createFile() const {
        QFile file(filePath);
        if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
            qDebug() << "Failed to create file:" << filePath;
            return false;
        }
        file.close();
        return true;
    }

    // 写入一行字符串到文件
    bool writeLine(const QString &line) const {
        QFile file(filePath);
        if (!file.open(QIODevice::Append | QIODevice::Text)) {
            qDebug() << "Failed to open file for writing:" << filePath;
            return false;
        }
        QTextStream out(&file);
        QStringList parts = line.split("|");
        if (parts.size() < 3) {
            qDebug() << "Invalid line format:" << line;
            file.close();
            return false;
        }
        QString id = parts[2].trimmed();
        if (idExists(id)) {
            qDebug() << "ID already exists:" << id;
            file.close();
            return false;
        }
        out << line << "\n";
        file.close();
        return true;
    }

    // 删除一行
    bool deleteLine(const QString &id) const {
        QFile file(filePath);
        if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
            qDebug() << "Failed to open file for reading:" << filePath;
            return false;
        }
        QStringList lines;
        QTextStream in(&file);
        while (!in.atEnd()) {
            QString line = in.readLine();
            QStringList parts = line.split("|");
            if (parts.size() >= 3 && parts[2].trimmed() != id) {
                lines << line;
            }
        }
        file.close();

        if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
            qDebug() << "Failed to open file for writing:" << filePath;
            return false;
        }
        QTextStream out(&file);
        for (const QString &line : lines) {
            out << line << "\n";
        }
        file.close();
        return true;
    }

    // 修改一行
    bool modifyLine(const QString &id, const QString &newLine) const {
        if (!deleteLine(id)) {
            return false;
        }
        return writeLine(newLine);
    }

    // 查询一行
    QString queryLine(const QString &searchString) const {
        QFile file(filePath);
        if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
            qDebug() << "Failed to open file for reading:" << filePath;
            return QString();
        }
        QTextStream in(&file);
        while (!in.atEnd()) {
            QString line = in.readLine();
            if (line.contains(searchString)) {
                file.close();
                return line;
            }
        }
        file.close();
        return QString();
    }

    bool deleteFile(const QString &fileName)
    {
        QFile file(fileName);
        return file.remove();
    }
    // 格式化文件
    void formatFile1() const {
        QFile file(filePath);
        if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
            qDebug() << "Failed to open file for reading:" << filePath;
            return;
        }
        QTextStream in(&file);
        QStringList lines;
        QVector<int> maxWidths(10, 0); // 假设最多有10列

        // 计算每一列的最大宽度
        while (!in.atEnd()) {
            QString line = in.readLine();
            QStringList parts = line.split("|");
            for (int i = 0; i < parts.size(); ++i) {
                int width = parts[i].trimmed().size();
                if (width > maxWidths[i]) {
                    maxWidths[i] = width + 10;
                }
            }
            lines << line;
        }
        file.close();

        // 重新格式化每一行
        if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
            qDebug() << "Failed to open file for writing:" << filePath;
            return;
        }
        QTextStream out(&file);
        for (const QString &line : lines) {
            QStringList parts = line.split("|");
            QString formattedLine;
            for (int i = 0; i < parts.size(); ++i) {
                formattedLine += parts[i].trimmed().leftJustified(maxWidths[i])  + " |";
            }
            qDebug() <<formattedLine;
            out << formattedLine << "\n";
        }
        file.close();
    }
    QString alignString(const QString &str, int width, const QFont &font) const {
        QFontMetrics metrics(font);
        int strWidth = metrics.width(str);
        if (strWidth < width) {
            return str.rightJustified(width); // 使用rightJustify为了左对齐
        }
        return str;
    }

    bool isChineseCharacter(QChar ch) const {
        // 汉字的Unicode编码范围是4E00-9FA5
        return ch.unicode() >= 0x4E00 && ch.unicode() <= 0x9FA5;
    }

    int getDisplayWidth(const QString &str) const{
        int width = 0;
        for (const QChar &ch : str) {
            // if (ch.isHighSurrogate() || ch.isLowSurrogate() || ch.isLetterOrNumber()) {
            if(!isChineseCharacter(ch)){
                width += 1;
            } else {
                width += 2;
            }
        }
        return width;
    }

    void formatFile2() const {
        QFile file(filePath);
        if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
            qDebug() << "Failed to open file for reading:" << filePath;
            return;
        }
        QTextStream in(&file);
        QStringList lines;
        QVector<int> maxWidths(10, 0); // 假设最多有10列

        // 计算每一列的最大宽度
        while (!in.atEnd()) {
            QString line = in.readLine();
            QStringList parts = line.split("|");
            for (int i = 0; i < parts.size(); ++i) {
                int width = getDisplayWidth(parts[i].trimmed());
                if (width > maxWidths[i]) {
                    qDebug() << parts[i].trimmed() <<":"<<width;
                    maxWidths[i] = width ;// + 10; // 额外增加10个空格
                }
            }
            lines << line;
        }
        file.close();

        // 重新格式化每一行
        if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
            qDebug() << "Failed to open file for writing:" << filePath;
            return;
        }
        QTextStream out(&file);
        for (const QString &line : lines) {
            QStringList parts = line.split("|");
            QString formattedLine;
            for (int i = 0; i < parts.size(); ++i) {
                QString trimmedPart = parts[i].trimmed();
                int currentWidth = getDisplayWidth(trimmedPart);
                int padding = maxWidths[i] - currentWidth;
                formattedLine += trimmedPart + QString(padding, ' ') + " |";
            }
            qDebug() << formattedLine;
            out << formattedLine << "\n";
        }
        file.close();
    }
private:
    QString filePath;

    // 检查ID是否存在
    bool idExists(const QString &id) const {
        QFile file(filePath);
        if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
            qDebug() << "Failed to open file for reading:" << filePath;
            return false;
        }
        QTextStream in(&file);
        while (!in.atEnd()) {
            QString line = in.readLine();
            QStringList parts = line.split("|");
            if (parts.size() >= 3 && parts[2].trimmed() == id) {
                file.close();
                return true;
            }
        }
        file.close();
        return false;
    }

};

void createConfigFile(const QString &fileName, const QString &content) {
    QFile file(fileName);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        // 处理错误，例如可以抛出异常或者返回错误标志
        return;
    }

    QTextStream out(&file);
    out << content;
    file.close();
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    // Widget w;
    // w.show();

    // QStringList inputLines = {
    //     "F10000   |                    |Computer                      |我的电脑                      |::{20D04FE0-3AEA-1069-A2D8-08002B30309D}",
    //     "F3       |                    |Explorer                      |资源管理器                    |explorer.exe /e,::{20D04FE0-3AEA-1069-A2D8-08002B30309D}",
    //     "F0       |                    |MyDocument                    |我的文档                      |explorer.exe",
    //     "F8       |                    |ie                            |IE浏览器                      |iexplore.exe",
    //     "F9       |                    |notepad                       |记事本                        |notepad"
    // };
    // processMultipleLines(inputLines, &w);


    QString filePath = "data0831.txt";
    FileManager fileManager(filePath);
    fileManager.deleteFile(filePath);
    // 检查文件是否存在，如果不存在则创建
    if (!fileManager.fileExists()) {
        if (!fileManager.createFile()) {
            qDebug() << "Failed to create file.";
            return -1;
        }

        // 插入初始数据
        QStringList inputLines = {
            "F100   |a |Computer |我的电脑|aaaaaaa",
            "F3       |bbb   |Explorer |资源管理器 | bbbbbbbbb",
            "F0       |cc   |MyDocument |我的文档|cccccc",
            "F8       |dddddd   |ie |IE浏览器 |dddddddd",
            "F9       |e |notepad |记事本 |notepad"
        };

        for (const QString &line : inputLines) {
            if (!fileManager.writeLine(line)) {
                qDebug() << "Failed to write line:" << line;
            }
        }
    }else{
        // fileManager.deleteFile(filePath);
    }
    // 格式化文件
    // fileManager.formatFile1();
    fileManager.formatFile2();
    int len = fileManager.getDisplayWidth("我的电脑a");
    qDebug() << "len=" << len;
    // 示例操作
    // qDebug() << "Query line containing 'Computer':" << fileManager.queryLine("Computer");
    // qDebug() << "Modify line with ID 'Computer':" << fileManager.modifyLine("Computer", "F100   |a |NewComputer |新的电脑|aaaaaaa");
    // qDebug() << "Delete line with ID 'Explorer':" << fileManager.deleteLine("Explorer");
    // qDebug() << "Write new line:" << fileManager.writeLine("F11   |f |NewEntry |新条目|fffffff");

    QStringList a1 = QStandardPaths::standardLocations(QStandardPaths::DesktopLocation);
    QStringList a2 = QStandardPaths::standardLocations(QStandardPaths::DocumentsLocation);
    QStringList a3 = QStandardPaths::standardLocations(QStandardPaths::ApplicationsLocation);
    QStringList a4 = QStandardPaths::standardLocations(QStandardPaths::TempLocation);
    QStringList a5 = QStandardPaths::standardLocations(QStandardPaths::AppDataLocation);
    QStringList a6 = QStandardPaths::standardLocations(QStandardPaths::AppLocalDataLocation);
    QStringList a7 = QStandardPaths::standardLocations(QStandardPaths::ConfigLocation);


    qDebug()<<"a1="<<a1;

    return a.exec();
}
